package com.jframe.sys.controller.listener;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;




import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.jframe.sys.controller.utils.Task;
import com.jframe.sys.controller.utils.TaskThread;
import com.jframe.sys.utils.FileUtil;
import com.jframe.sys.utils.JsonUtil;
import com.jframe.sys.utils.PropertiesUtil;
import com.jframe.sys.utils.StringUtil;


public class ThreadListener implements ServletContextListener {

	Set<TaskThread> threads = new HashSet<TaskThread>();

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		this.start(arg0); // 线程启动
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		// this.taskThread.stopThread();
		this.stop();
	}

	private void start(ServletContextEvent arg0) {
		Map<String, Task> map = new load().loadAll();
		Set<String> keySet = map.keySet();
		for (String key : keySet) {
			Task task = map.get(key);
			String[] args = StringUtil.split(task.getArgs());
			
			TaskThread thread = new TaskThread(key, task.getAction(), task
					.getMethod(),this.getArgs(args, arg0), this.getMsSleep(task.getSleep(), task.getSleepUnit()));
			threads.add(thread); 
			thread.start();
		}
	}
	
	private Object[] getArgs(String[] args,ServletContextEvent arg0){
		if(args==null){
			return new Object[]{arg0};
		}else{
			Object[] objs = new Object[args.length+1];
			objs[0]=arg0;
			for(int i=1;i<args.length+1;i++){
				objs[i]=args[i-1];
			}			
			return objs;
		}
		
	}

	private void stop() {
		for (TaskThread thread : threads) {
			thread.stopThread();
		}
	}

	private long getMsSleep(long sleep, int sleepUnit) {

		// 1:毫秒
		if (sleepUnit == 1) {
			return sleep;
		} else if (sleepUnit == 2) {
			return sleep * 1000;
		} else if (sleepUnit == 3) { // 分
			return sleep * 1000 * 60;
		} else if (sleepUnit == 4) { // 小时
			return sleep * 1000 * 60 * 60;
		} else if (sleepUnit == 5) {
			return sleep * 1000 * 60 * 24 * 60;
		} else if (sleepUnit == 6) {
			return sleep * 1000 * 60 * 24 * 60 * 30;
		} else if (sleepUnit == 7) {
			return sleep * 1000 * 60 * 24 * 60 * 30 * 365;
		} else {
			return sleep > 1000 ? sleep : sleep * 1000; //如果用户没有选择单位，那么大于1000的默认为妙，否则为毫秒
		}
	}

	

	static class load {

		Map<String, Task> loadAll() {
			String path = "/"+StringUtil.getPrjAbsolutePath()+ "WEB-INF/classes/"; //linux
			String[] files = this.findAllActionProperties();
			Map<String, Task> map = new HashMap<String, Task>();
			for (String file : files) {
				map.putAll(this.loadProperties(path+file));
			}
			return map;
		}

		String[] findAllActionProperties() {
			String path = "/"+StringUtil.getPrjAbsolutePath()+ "WEB-INF/classes/"; //linux
			
			//String path = StringUtil.getPrjAbsolutePath()+ "WEB-INF/classes/";  //windows
			String[] files = FileUtil.getFileList(path,
					"taskThread-config*.properties");

			return files;
		}

		Map<String, Task> loadProperties(String file) {

			PropertiesUtil props = PropertiesUtil.getInstance(file);
			Map<String, String> map = props.loadAll();
			return setClassCache(map);
		}

		Map<String, Task> setClassCache(Map<String, String> map) {
			Set<String> keySet = map.keySet();
			Iterator<String> it = keySet.iterator();
			Map<String, Task> tasks = new HashMap<String, Task>();
			while (it.hasNext()) {
				String key = StringUtil.null2Space(it.next()).trim();
				try {
					String taskCfg = map.get(key);
					Task task = (Task) JsonUtil.json2Obj(taskCfg, Task.class);
					tasks.put(key, task);
				} catch (Exception ex) {
					 ex.printStackTrace();
					// System.out.println(key + "对应的类不存在！");
				}
			}
			return tasks;
		}
		
		

	}
}
